# -*- coding: utf-8 -*-
"""
HaaS506 RTU 时间同步模块
提供HTTP时间同步和RTC管理功能
"""

import utime
import usocket as socket
import ujson as json
from driver import RTC
import rtu_config
import rtu_storage
import rtu_system

# 时间同步状态
_time_synced = False
_last_sync_time = 0
_sync_interval = 600  # 10分钟
_rtc = None

# 最早时间2025-01-01
MIN_TIMESTAMP = 1735660800


def init():
    """初始化时间模块"""
    global _sync_interval, _rtc

    try:
        # 初始化RTC
        _rtc = RTC()
        _rtc.open()

        _sync_interval = rtu_config.get_config("intervals.time_sync", 600)

        # 检查是否需要使用缓存时间
        if rtu_system.should_use_cached_time():
            cached_time = rtu_system.get_cached_timestamp()
            if cached_time > 0:
                print(
                    "[TIME] Using cached timestamp: {} ({})".format(
                        cached_time, _format_time(cached_time)
                    )
                )
                _set_rtc_time(cached_time)
                print("[TIME] RTC restored from cache")

        print("[TIME] Time module initialized")
        return True
    except Exception as e:
        print("[TIME] Init error: {}".format(e))
        return False


def sync_time():
    """同步时间"""
    global _time_synced, _last_sync_time

    try:
        # 使用HTTP时间同步
        if _sync_time_http():
            _time_synced = True
            _last_sync_time = utime.time()
            rtu_config.g_time_synced = True

            # 保存同步时间
            rtu_storage.save_system_time()
            # 保存到系统模块
            rtu_system.save_last_timestamp()

            print("[TIME] Time synchronized successfully")
            return True

        print("[TIME] Time sync failed")

        # 同步失败，尝试使用缓存时间
        if rtu_system.should_use_cached_time():
            cached_time = rtu_system.get_cached_timestamp()
            if cached_time > 0:
                print("[TIME] Using cached time due to sync failure")
                _set_rtc_time(cached_time)
                _time_synced = False  # 标记为未同步
                rtu_config.g_time_synced = False
                return True  # 返回True表示时间已设置

        return False

    except Exception as e:
        print("[TIME] Sync time error: {}".format(e))
        return False


def _sync_time_http():
    """HTTP时间同步"""
    sock = None
    try:
        time_server = rtu_config.get_config(
            "servers.time_server", "dtu.coldwang.com/api/time"
        )
        timeout = rtu_config.get_config("servers.time_timeout", 10)

        # 解析服务器URL
        if time_server.startswith("http://"):
            time_server = time_server[7:]

        parts = time_server.split("/", 1)
        host = parts[0]
        path = "/" + (parts[1] if len(parts) > 1 else "")

        print("[TIME] Syncing time from {}{}".format(host, path))

        # 创建socket连接
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(timeout)

        try:
            addr = socket.getaddrinfo(host, 80)[0][-1]
            sock.connect(addr)
        except Exception as e:
            print("[TIME] Socket connect error: {}".format(e))
            return False
        imei = ""
        ccid = ""
        from modem import sim

        # 获取IMEI
        try:
            imei = sim.getImei() or ""
        except:
            imei = ""

        # 获取CCID
        try:
            ccid = sim.getIccid() or ""
        except:
            ccid = ""

            # 构建请求，包含当前版本信息和设备编号
        request_data = {
            "action": "time_sync",
            "current_version": rtu_config.get_config("system.version"),
            "device_sn": rtu_config.get_config("device.device_sn"),
            "device_type": "haas506_dtu",
            "imei": imei,
            "ccid": ccid,
        }
        print("[TIME] request_data: {}".format(request_data))
        # request = "GET {} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\n\r\n".format(
        #     path, host
        # )
        request = "POST {} HTTP/1.1\r\nHost: {}\r\nContent-Type: application/json\r\nConnection: close\r\nContent-Length: {}\r\n\r\n{}".format(
            path, host, len(json.dumps(request_data)), json.dumps(request_data)
        )
        sock.send(request.encode())

        # 读取响应 - 限制最大读取大小为4KB
        response = b""
        max_size = 4096
        while len(response) < max_size:
            try:
                chunk = sock.recv(1024)
                if not chunk:
                    break
                response += chunk
            except Exception:
                break

        # 解析响应
        response_str = response.decode("utf-8", "ignore")

        if "200 OK" not in response_str:
            print("[TIME] Server returned non-200 response")
            return False

        # 提取JSON数据
        json_start = response_str.find("\r\n\r\n")
        if json_start == -1:
            json_start = response_str.find("\n\n") + 2
        else:
            json_start += 4

        # 限制JSON数据大小
        json_str = response_str[json_start : json_start + 1024]

        try:
            data = json.loads(json_str)
        except ValueError:
            print("[TIME] Invalid JSON response")
            return False

        if "timestamp" in data:
            timestamp = data["timestamp"]

            # 验证时间戳有效性
            if timestamp < MIN_TIMESTAMP:
                print("[TIME] Invalid timestamp: {}".format(timestamp))
                return False

            # 设置系统时间
            if _set_rtc_time(timestamp):
                print("[TIME] Time set to: {}".format(get_current_time()))
                return True
            else:
                return False
        else:
            print("[TIME] No timestamp in response")
            return False

    except Exception as e:
        print("[TIME] HTTP sync error: {}".format(e))
        return False
    finally:
        # 确保socket被关闭
        if sock:
            try:
                sock.close()
            except:
                pass


def get_current_time():
    """获取当前时间字符串"""
    try:
        tm = utime.localtime()
        return "{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(
            tm[0], tm[1], tm[2], tm[3], tm[4], tm[5]
        )
    except:
        return "Unknown"


def get_current_timestamp():
    """获取当前时间戳"""
    return int(utime.time())


def check_sync_needed():
    """检查是否需要同步时间"""
    global _last_sync_time

    # 检查时间间隔
    current_time = utime.time()
    if current_time - _last_sync_time < _sync_interval:
        return False

    # 检查时间有效性
    if current_time < MIN_TIMESTAMP:
        return True

    return True


def get_time_status():
    """获取时间模块状态"""
    return {
        "time_synced": _time_synced,
        "last_sync_time": _last_sync_time,
        "current_time": get_current_time(),
        "current_timestamp": get_current_timestamp(),
    }


def _set_rtc_time(timestamp):
    """设置RTC时间"""
    try:
        if _rtc:
            # 使用 gmtime 确保设置的是 UTC 时间
            tm = utime.gmtime(timestamp)
            # 使用 setTime 方法设置时间
            _rtc.setTime(tm[0], tm[1], tm[2], tm[3], tm[4], tm[5])
            return True
        else:
            print("[TIME] RTC not available")
            return False
    except Exception as e:
        print("[TIME] Set RTC time error: {}".format(e))
        return False


def _format_time(timestamp):
    """格式化时间戳"""
    try:
        tm = utime.localtime(timestamp)
        return "{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(
            tm[0], tm[1], tm[2], tm[3], tm[4], tm[5]
        )
    except:
        return str(timestamp)


def test_time():
    """测试时间功能"""
    print("[TIME] Testing time functionality...")

    # 测试当前时间
    print("[TIME] Current time: {}".format(get_current_time()))
    print("[TIME] Current timestamp: {}".format(get_current_timestamp()))

    # 测试时间同步
    print("[TIME] Testing time sync...")
    if sync_time():
        print("[TIME] Time sync test passed")
    else:
        print("[TIME] Time sync test failed")

    # 显示时间状态
    status = get_time_status()
    print("[TIME] Time status: {}".format(status))

    print("[TIME] Time test completed")
